import { Button, Card, Form, Input, Table, message } from "antd";
import React, { useEffect, useState } from "react";
import {
  reqDeletHosByID,
  reqHospitalSetList,
  reqDeleteBatchHos,
} from "@api/hospitalSet";
import {
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import styles from "./index.module.less"; //ts必须要有配置文件规定类型
import { type hosSetListType, hosSetListItemType } from "@/api/hospitalSet";
import { useNavigate } from "react-router-dom";
import { Key } from "antd/es/table/interface";

export default function HospitalSet() {
  const [messageApi, contetHolder] = message.useMessage();

  const navigate = useNavigate();

  //数据1：页码的当前页
  const [current, setCurrent] = useState<number>(1);
  //数据2： 数据总数
  const [total, setTotal] = useState<number>(0);
  //数据3：每页条数
  const [pageSize, setPageSize] = useState(3);
  //数据4：医院列表数据
  const [hospitalList, setHospitalList] = useState<hosSetListType>([]);

  // 数据5：loading状态
  const [idList, setIdList] = useState<Key[]>([]);

  const [isLoading, setIsLoading] = useState(false);

  const [form] = Form.useForm(); //from实例

  // //请求医院列表数据类型
  //  interface getHospitalListParamType {
  //   hosname?:string; /* ?-添加类型undefined */
  //   hoscode?:string;
  //  }
  // // 方法1：请求医院列表函数
  //  const getHospitalList = async ({hosname,hoscode}:getHospitalListParamType)=>{

  const getHospitalList = async () => {
    setIsLoading(true);
    const { hosname, hoscode } = form.getFieldsValue();
    const result = await reqHospitalSetList({
      page: current,
      limit: pageSize,
      hosname,
      hoscode,
    });

    setHospitalList(result.records);
    //设置医院列表数据
    setTotal(result.total);
    //设置数据总条数
    setIsLoading(false);
  };

  // 方法2：表单提交事件回调函数
  const searchFinish = () => {
    getHospitalList();
  };

  //方法3：清空表单回调函数
  const resetForm = () => {
    //form实例上有一个resetFields方法,可以重置表单
    form.resetFields();
    //当查询表单被清空的时候,需要重新发送请求
    getHospitalList();
  };

  //方法4：点击页码 数据响应式更改
  const pageChange = (page: number, pageSize: number) => {
    setCurrent(page);
    setPageSize(pageSize);
  };
  //方法5： 加载添加新页面事件回调函数
  const addHos = () => {
    navigate("/syt/hospital/add");
  };

  //方法6：修改医院数据回调函数
  const updateHos = (id: number) => {
    return () => {
      navigate(`/syt/hospital/update/${id}`);
    };
  };

  //方法7 ：根据id删除单个医院
  const batchDelete = async () => {
    await reqDeleteBatchHos(idList as number[]);

    messageApi.open({
      type: "success",
      content: "批量删除医院成功",
    });
    getHospitalList();
  };

  const deleteHos = (id: number) => {
    return async () => {
      await reqDeletHosByID(id);
      messageApi.open({
        type: "success",
        content: "删除医院成功",
      });
      getHospitalList(); //重新渲染
    };
  };

  const rowSelection = {
    async onChange(idList: Key[]) {
      setIdList(idList);
    },
  };

  //在虚拟DOM挂载时调用渲染数据
  useEffect(() => {
    getHospitalList();
  }, [current, pageSize]);

  const columns = [
    {
      title: "序号",
      render(_: any, __: any, index: number) {
        /* 接收三个参数 前两个没用 _站位 */
        return index + 1;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
      // 关联dataIndex
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
    },
    {
      title: "签名",
      dataIndex: "signKey",
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
    },
    {
      title: "联系人手机",
      dataIndex: "contactsPhone",
    },
    {
      title: "操作",
      width: "120px",
      fixed: "right" as "right",
      render(row: hosSetListItemType) {
        return (
          <div>
            <Button
              icon={<EditOutlined />}
              type="primary"
              className={styles.mr}
              onClick={updateHos(row.id)}
            ></Button>
            {/* icon小图标 */}
            <Button
              icon={<DeleteOutlined />}
              danger
              type="primary"
              onClick={deleteHos(row.id)}
            ></Button>
          </div>
        );
      },
    },
  ];

  return (
    <Card>
      {/* 卡片组件 */}
      {contetHolder}
      <Form
        layout="inline"
        className={styles.mb}
        onFinish={searchFinish}
        form={form}
      >
        {/* module.less 加密处理less样式 */}
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>
        <Form.Item>
          <Button icon={<SearchOutlined />} type="primary" htmlType="submit">
            查询
          </Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={resetForm}>清空</Button>
        </Form.Item>
      </Form>
      <div className={styles.mb}>
        <Button type="primary" className={styles.mr} onClick={addHos}>
          添加
        </Button>
        <Button
          type="primary"
          danger
          disabled={idList.length === 0}
          onClick={batchDelete}
        >
          批量删除
        </Button>
        {/* danger 警示按钮属性 */}
      </div>

      <Table
        dataSource={hospitalList} /* 假数据 */
        columns={columns} /* 表格每列类型 */
        bordered
        rowSelection={rowSelection} /* 行选择  */
        rowKey={(row) => row.id} /* id选择 */
        scroll={{ x: 1200 }} /* 滚动行 */
        loading={isLoading}
        pagination={{
          total: total,
          //数据总数
          current: current,
          //当前页码
          pageSize: pageSize /* 改为响应式 */,
          //每一页条数
          showSizeChanger: true,
          //是否展示pageSize选择器
          pageSizeOptions: [3, 5, 7, 10],
          //pageSize选择器的选项
          onChange: pageChange,
        }}
      />
    </Card>
  );
}
